const axios = require('axios');
import api from './api'
import mock from './mock.data'
import { Message } from 'element-ui'
import router from '../router_1'

function mockdata (fun, cb) {
	cb(mock[fun]);
}

export default ({ mock, fun, cb, err, requestType, ...data }) =>  {

	if(mock){
		mockdata(fun, cb);
		return;
	}

	const url = api[fun];

	//默认post请求。
	const method = requestType == 'get' ? 'GET' : 'POST';

	//把空属性去掉。
	Object.keys(data).forEach(key => {
		if(data[key] === undefined){
			delete data[key];
		}else{
			let v = data[key];
			if(typeof(v) == 'string'){
				data[key] = v.trim();
			}
		}
	});

	let config = {
		method,
		url,
	};

	config['headers'] = {
		'Content-Type' : 'application/json',
	};

	if(method == 'GET'){
		config['params'] = data;
	}else if(method == 'POST'){
		config['data'] = data;
	}

	axios(config)
	.then(res => {
		console.log(res);
		if(res.data.errcode == 0){
			if(cb) cb(res.data.data);
		}else if(res.data.errcode == 1001){
			console.log(url);
			console.log(res.data.errmsg);
			router.push({ 
				name: 'login', 
			});
			return;
		}else{
			console.log(url);
			console.log(res.data.errmsg);
			if(err){
				err(res.data.errmsg);
			}else{
				Message({
					message: res.data.errmsg,
					type: 'error',
					duration: 5 * 1000
				})
			}
		}
	})
	.catch(res => {
		console.log('http 中的异常')
		console.log(res);
	})

}